package com.reny.ll.git.base_logic.api

import com.reny.ll.git.base_logic.MViewModel
import com.reny.ll.git.base_logic.ext.loge
import com.reny.ll.git.base_logic.ext.toast
import com.reny.ll.git.base_logic.hideLoading
import com.reny.ll.git.mvvm.NetUtils
import com.reny.ll.git.mvvm.extras.postNext
import com.reny.ll.git.mvvm.state.STATE_ERROR
import com.reny.ll.git.mvvm.state.STATE_NO_NETWORK

fun MViewModel.exceptionProcess(
    popToast: Boolean = true,
    otherHandle: ((HttpException) -> Unit)? = null
): ((Throwable) -> Unit)?{
    return { it ->
        hideLoading()

        loge("${this.javaClass.simpleName} >> exception ${it.message}")
        if (popToast) {
            toast(it.message ?: if(it is HttpException) "Error Code: ${it.code}" else "")
        }

        if (isFirst) {
            setLoadState(
                if (NetUtils.isConn()) STATE_ERROR else STATE_NO_NETWORK,
                noMore = true,
                isRefresh = true
            )
        } else {
            refreshState.postNext {
                it.copy(noMore = false)
            }
        }
        otherHandle?.let { func ->
            if(it is HttpException){
                func(it)
            } else{
                func(HttpException(message = it.message ?: ""))
            }
        }
    }
}